﻿using System;
using Castle.DynamicProxy;
using Sapit.Base;
using Sapit.Helpers;
using Sapit.Windsor.Attributes;

namespace Sapit.Windsor
{
    public class ResponseTimeThrottleInterceptor : ResponseTimeThrottleBase, IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            Invocation inv = new Invocation() { InvocationTarget = invocation.InvocationTarget, Method = invocation.Method };

            var responseTimeThrottle = AttributeHelper.GetAttributeIfPresent<ResponseTimeThrottleAttribute>(invocation.Method);
            if (responseTimeThrottle != null)
            {
                    if (IsThisInvocationThrottled(inv))
                    {
                        DecrementThrottleCounterForThisInvocation(inv);

                        switch (responseTimeThrottle.BehaviorWhenThrottling)
                        {
                            case Behavior.Undefined:
                            case Behavior.ReturnDefaultValue:
                                invocation.ReturnValue = responseTimeThrottle.ThrottleReturnValue;
                                break;
                            case Behavior.ThrowException:
                                throw new InvalidOperationException(string.Format("{0}", responseTimeThrottle.ThrottleReturnValue));
                            default:
                                invocation.ReturnValue = responseTimeThrottle.ThrottleReturnValue;
                                break;
                        }
                    }
                    else
                    {
                        UnThrottleThisInvocation(inv);
                        double responseTime = InvokeMethodAndRecordResponseTime(invocation);
                        if (responseTime > responseTimeThrottle.ThrottleThresholdMilliseconds)
                        {
                            ThrottleThisInvocation(inv, responseTimeThrottle.SkipCallsWhenThrottling);
                        }
                    }
            }
            else
            {
                invocation.Proceed();
            }
        }

        private static double InvokeMethodAndRecordResponseTime(IInvocation invocation)
        {
            DateTime beforeInvocation = DateTime.Now;
            invocation.Proceed();
            DateTime afterInvocation = DateTime.Now;
            return (afterInvocation - beforeInvocation).TotalMilliseconds;
        }
    }
}
